<template>
  <div>
    <div id="container"></div>
    <el-button 
      :class="ismobile ? 'modebutton' : 'mobile_modebutton'"
      size="mini" 
      type="text"
      v-if="buttonshow" 
      @click="changecornor()">
      <i
        :class="iscornor ? 'el-icon-view' : 'el-icon-video-play'"
        class="backPage"
        >{{ iscornor ? "监测" : "演示" }}</i
      >
    </el-button>
  </div>
</template>

<script>
// import { mapState } from "vuex";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";
import { mapState } from 'vuex'
// import {
//   CSS2DRenderer,
//   CSS2DObject
// } from "three/examples/jsm/renderers/CSS2DRenderer.js";

export default {
  data() {
    return {
      rotateFlage: 1,
      times: null,
      // 目标角度
      // fangxiang
      center:-84,
      iscornor:2,
      // 停止旋转
      stoptime:0,
      // 手机是否
      ismobile:1,
      buttonshow:false,
      // 演示角度
      showcornor:0,
    };
  },
  // 测试
  // vuex数据引入
  computed:{
    ...mapState([
    'cornor',
    ])
  },
  methods: {
    test() {
      var that = this
      let container = document.getElementById("container");
      //模型
      var model = new THREE.Group(); //声明一个组对象，用来添加加载成功的三维场景
      var model2 = new THREE.Group(); //声明一个组对象，用来添加加载成功的三维场景
      var model3 = new THREE.Group(); //声明一个组对象，用来添加加载成功的三维场景
      var model4 = new THREE.Group(); //声明一个组对象，用来添加加载成功的三维场景
      var loader = new GLTFLoader(); //创建一个GLTF加载器
      var dracoLoader = new DRACOLoader()
      dracoLoader.setDecoderPath('/draco/');
      loader.setDRACOLoader(dracoLoader)
      // loader.load("XIANGBEIDraco.glb", function(gltf) {
      loader.load("http://cdn.hustzjc.top/XIANGBEIDraco.glb", function (gltf) {

        //gltf加载成功后返回一个对象
        // console.log('控制台查看gltf对象结构', gltf);
        // console.log('gltf对象场景属性', gltf.scene);
        // 递归遍历gltf.scene
        that.$emit('modeload')
        gltf.scene.traverse(function (object) {
          if (object.type === "Mesh") {
            // 批量更改所有Mesh的材质
            object.material = new THREE.MeshLambertMaterial({
              map: object.material.map, //获取原来材质的颜色贴图属性值
              color: object.material.color //读取原来材质的颜色
            });
          }
        });
        //把gltf.scene中的所有模型添加到model组对象中
        model.add(gltf.scene.getObjectByName("主体"));
        model2.add(gltf.scene.getObjectByName("底座"));
        model3.add(gltf.scene.getObjectByName("红区"));
        model4.add(gltf.scene.getObjectByName("绿区"));
        // console.log('model属性：',model)
        // model.add(gltf.scene);
      });

      var scene = new THREE.Scene();

      //角度和弧度转换公式：角度 * (Math.PI / 180）
      // fangxiang
      model.rotateY(84 * (Math.PI / 180))

      //  model.children.forEach(element => {console.log('遍历的结果：',element)});
      //查看场景
      // console.log("场景", scene);

      scene.add(model);
      scene.add(model2);
      scene.add(model3);
      scene.add(model4);


      // 模型位置初步处理
      // console.log('模型信息',model.position.y);
      // model.position.y = -0.5

      // 设置雾化效果，雾的颜色和背景颜色相近，这样远处网格线和背景颜色融为一体
      scene.fog = new THREE.Fog(0x005577, -100, 10000);

      // 平行光1
      var directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
      directionalLight.position.set(400, 200, 300);
      scene.add(directionalLight);
      // 平行光2
      var directionalLight2 = new THREE.DirectionalLight(0xffffff, 0.5);
      directionalLight2.position.set(-400, -200, -300);
      scene.add(directionalLight2);
      //环境光
      var ambient = new THREE.AmbientLight(0xffffff, 0.4);
      scene.add(ambient);

      //画布设置、相机设置

      var width = window.innerWidth; //窗口文档显示区的宽度
      var height = window.innerHeight; //窗口文档显示区的高度
      if (width < height) {
        let num2 = width
        width = height
        height = num2
      }

      var k = width / height; //Three.js输出的Canvas画布宽高比
      // var s = 200; //控制相机渲染空间左右上下渲染范围，s越大，相机渲染范围越大
      // var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
      // camera.position.set(200, 300, 200); //相机在Three.js坐标系中的位置
      // camera.lookAt(0, 0, 0); //相机指向Three.js坐标系原点
      var camera = new THREE.PerspectiveCamera(45, k, 1, 3000);
      // 相机视角位置，可以调整
      camera.position.set(600, 350, 400); //通过相机控件OrbitControls旋转相机，选择一个合适场景渲染角度
      if(navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      )){
        let width = document.documentElement.clientWidth;
        let height = document.documentElement.clientHeight;
        let k = width / height;
        if(k <= 1.5){
          camera.position.set(700, 500, 800);
        }
      }
      camera.lookAt(0, 0, 0);
      var renderer = new THREE.WebGLRenderer({
        antialias: true, //开启锯齿
        alpha: true
      });

      // console.log("渲染器", renderer);

      renderer.setPixelRatio(window.devicePixelRatio); //设置设备像素比率,防止Canvas画布输出模糊。
      renderer.setSize(width, height); //设置渲染区域尺寸
      renderer.setClearColor(0x021B30, 0.0); //设置背景颜色背景透明
      renderer.outputEncoding = THREE.sRGBEncoding; //解决加载gltf格式模型纹理贴图和原图不一样问题

      // renderer.domElement表示Three.js渲染结果,也就是一个HTML元素(Canvas画布)，下面就是打印一下
      // console.log("canvas画布", renderer.domElement);

      container.appendChild(renderer.domElement); //body元素中插入canvas画布
      //执行渲染操作 
      // 场景变化
      window.addEventListener("resize", onWindowResize, false);
      function onWindowResize() { 
        renderer.setSize(window.innerWidth, window.innerHeight);
        // labelRenderer.setSize( window.innerWidth, window.innerHeight );
      }
      // 渲染循环
      function render() {
        if (that.rotateFlage == 0) {
          // 设置单帧转动的角度
          model.rotateY(that.center / 800 * (Math.PI / 180));
          // console.log('当前角度',model.rotation._y / (Math.PI / 180));
          that.times += 1;
          if (that.times >= 800) {
            that.rotateFlage = 1
            setTimeout(() => {
              that.times = 0
              that.center = -that.center
              that.rotateFlage = 0
            }, 2000);
          }
        }
        // 显示当前角度
        if(that.iscornor == 0){
          let cornornow = model.rotation._y/(Math.PI / 180)
          that.rotateFlage = 1
          // fangxiang
          let cornor = 84 - that.cornor
          model.rotateY((cornor - cornornow)*(Math.PI / 180))
        }else if (that.iscornor == 1){
          let cornornow1 = model.rotation._y/(Math.PI / 180)
          // fangxiang
          model.rotateY((83.99999 - cornornow1)*(Math.PI / 180))
          that.rotateFlage = 0
          that.times = 0
          that.center = -84
          that.iscornor = 2
        }

        // model.rotateY(0.01); //立方体绕y轴旋转动画
        renderer.render(scene, camera); //执行渲染操作
        requestAnimationFrame(render); //请求再次执行渲染函数render，渲染下一帧
      }
      render();

      
      //创建控件对象  控件可以监听鼠标的变化，改变相机对象的属性
      var controls = new OrbitControls(camera, renderer.domElement); // eslint-disable-line no-unused-vars
    },
    keeper() {
      setTimeout(() => {
        this.rotateFlage = 0;
        this.times = 0;
      }, 2000);
    },
    changecornor(){
      if(this.iscornor > 0){
        this.iscornor = 0
      }else{
        this.iscornor = 1
      }
    },
    _isMobile() {
      let flag = navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      );
      return flag;
    },
    renderResize() {
      // 判断横竖屏
      let width = document.documentElement.clientWidth;
      let height = document.documentElement.clientHeight;
      if (width > height) {
        this.$nextTick(() => {
          this.buttonshow = true;
        });
      } else {     
        this.$nextTick(() => {
          this.buttonshow = false;
        });
      }
      // 注意：renderResize 方法执行时虚拟 dom 尚未渲染挂载，如果要操作 vue 实例，最好在this.$nextTick()里进行。
    },
    changefontsize() {
      let width = document.documentElement.clientWidth;
      let height = document.documentElement.clientHeight;
      let k = width / height;
      if (k <= 1.5) {
        // 更改button
        var changebutton = document.querySelectorAll(".mobile_modebutton");
        changebutton[0].style.setProperty("right", "cacl(23vw - 90px)");
      }
    },
  },
  // computed: {
  //   ...mapState(["projectInfo", "userInfo"])
  // },
  created() {
    this.keeper()
    // 判断手机
    if(this._isMobile()){
      this.ismobile = 0
    }
    this.renderResize()
  },
  mounted(){
    // 监听resize方法
    window.addEventListener("resize", this.renderResize, false);
  },
  // 数据更新阶段再判断是否ipad
  updated(){
    if(this._isMobile()){
      this.changefontsize();
    }
  },
  beforeDestroy() {
    // 移除监听
    window.removeEventListener("resize", this.renderResize, false);
  },
  

};
</script>

<style scoped>

  /* pc模型出 */
  .modebutton {
    position:absolute;
    z-index: 2;
    top: 86%;
    /* 位置 */
    left:calc(50% - 45px);
    pointer-events: auto;
    font-size: 25px;
    color:#1296db;;
    background-color: rgba(13, 55, 139, 0.432) !important;
    letter-spacing:3px;
    opacity: 0.7;
  }
  .modebutton:hover{
    color: #fff;
    background-color: rgba(9, 87, 245, 0.432) !important;
    opacity: 1.0;
  }

  .mobile_modebutton{
    position:absolute;
    z-index: 2;
    top: 0%;
    right:calc(23vw - 46px);
    pointer-events: auto;
  }
  

</style>